from django.core.management.base import BaseCommand, CommandError
from apps.order.models import *
from apps.message.models import *
from apps.product.models import *
from apps.repo.models import *
from datetime import timedelta
import time
from django.db import transaction
import sys

class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argument('repo_id', type=str)
        parser.add_argument('count', type=int)
        parser.add_argument('parent_type', type=str)

    def handle(self, *args, **options):
        print(time.time())
        repo_id = options.get('repo_id')
        count = options.get('count')
        parent_type = options.get('parent_type')

        repo = Repo.objects.get(pk=repo_id)
        # 参数
        # 检查参数
        if parent_type == "a":
            su_parent_type = StoreUnit.ParentType.CROWD_BOX_V1.name
        elif parent_type == "b":
            su_parent_type = StoreUnit.ParentType.CHEST_V1.name
        else:
            raise Exception('Parent Type Error')

        last_store_unit = StoreUnit.objects.filter(parent_type=su_parent_type).last()
        generated_store_units = []
        if last_store_unit:
            last_int_fields = last_store_unit.get_int_fields()
        else:
            last_int_fields = None
        for i in range(count):
            next_int_fields = StoreUnit.get_next_int_fields(last_int_fields)
            if next_int_fields is None:
                break
            next_fields = [int_2_2d(next_int_fields[i]) if i in [0, 3, 5, 7] else chr(next_int_fields[i]) for i in range(len(next_int_fields))]
            next_fields[0] = next_fields[0][-1]

            # 生成StoreUnit对象，等待批量创建
            su = StoreUnit(repo=repo,
                           parent_type=su_parent_type,
                           no=next_fields[-1],
                           fields=next_fields[:-1],
                           repo_no=''.join(next_fields),
                           in_use=False
                           )
            generated_store_units.append(su)

            # 初始化下一次的种子
            last_int_fields = copy.copy(next_int_fields)

        # 批量创建
        StoreUnit.objects.bulk_create(generated_store_units)
        print('Count: %d Success: %d' % (count, len(generated_store_units)))
        print(time.time())